//
//  HttpUtil.m
//  PayDemoIOS
//
//  Created by 杨红军 on 17/12/12.
//  Copyright © 2017年 zpon. All rights reserved.
//

#import "HttpUtil.h"

@implementation HttpUtil

+ (void)post:(NSString *)url params:(NSDictionary *)params successCallback:(void (^)(NSDictionary *))successCallback failCallback:(void (^)(NSError *))failCallback{
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:(30)];
    [request setValue:@"Content-Type" forHTTPHeaderField:@"application/x-www-form-urlencoded"];
    [request setHTTPBody:[self params2Data:params]];
    [request setHTTPMethod:@"POST"];
    NSURLSession *sharedSession = [NSURLSession sharedSession];
    NSURLSessionTask *task = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSHTTPURLResponse *responses = (NSHTTPURLResponse*)response;
            if (responses.statusCode==200) {
                NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL];
                if (successCallback!=nil) {
                    successCallback(dic);
                }
            }else{
                if (failCallback!=nil) {
                    failCallback(error);
                }
            }
        });
    }];
    
    [task resume];
}

+ (NSData*)params2Data:(NSDictionary*)parmas{
    NSMutableData *data = [NSMutableData data];
    NSMutableString *tempStr = [NSMutableString string];
    for(NSString*key in parmas.allKeys){
        [tempStr appendFormat:@"%@=%@&",key,parmas[key]];
    }
    if (tempStr.length>0) {
        NSString *paramsStr=[tempStr substringWithRange: NSMakeRange(0, tempStr.length-1)];
        NSLog(@"字符串是:%@",paramsStr);
        [data appendData:[paramsStr dataUsingEncoding:NSUTF8StringEncoding]];
    }
    return data;
}
@end
